<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-01-31 10:54:34
 * @LastEditors: Andy
 * @LastEditTime: 2023-01-31 18:49:33
-->
<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="40%">
    <el-form :model="params" :rules="rules" ref="params" class="demo-form-inline" label-position="top">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.senderName')" prop="mailPersonal">
            <el-input
              v-model="params.mailPersonal"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.senderAddress')" prop="sender">
            <el-input
              v-model="params.sender"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.smtpAddress')" prop="mailHost">
            <el-input
              v-model="params.mailHost"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.smtpPort')" prop="mailPort">
            <el-input
              v-model="params.mailPort"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.userName')" prop="username">
            <el-input
              v-model="params.username"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.pwd')" prop="password">
            <el-input
              v-if="params?.id && !editPwd"
              type="password"
              v-model="params.password"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
            <el-input
              v-else
              v-model="params.password"
              :placeholder="$t('resourceAdmin.emailSet.placeHolderInput')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.certification')" prop="mechanisms">
            <x-select
              v-model="params.mechanisms"
              :options="dictOptions['msg_mail_setting.mechanisms']"
              style="width: 100%"
              :placeholder="$t('maintain.logMail.placeHolderStatus')"
              clearable
            ></x-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.logVerification')" prop="auth">
            <x-radio-group :list-data="dictOptions['msg_mail_setting.auth']" v-model="params.auth"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.ssl')" prop="smtpSsl">
            <x-radio-group
              :list-data="dictOptions['msg_mail_setting.smtp_ssl']"
              v-model="params.smtpSsl"
            ></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.tls')" prop="tls">
            <x-radio-group :list-data="dictOptions['msg_mail_setting.tls']" v-model="params.tls"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.emailSet.state')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, checkEmail } from '@package/utils'
  import { apiPostAddMailSetting, apiPutEditMailSetting } from '../api/email.js'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    props: {
      dictOptions: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: this.$t('resourceAdmin.emailSet.add'),
        params: {
          mailHost: '',
          mailPort: '',
          username: '',
          password: '',
          auth: 'true',
          mechanisms: '',
          smtpSsl: 'true',
          tls: 'true',
          sender: '',
          mailPersonal: '',
          state: '1'
        },
        editPwd: false,
        rules: {
          mailHost: [
            { required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'blur' },
            { min: 1, max: 50, message: this.$t('resourceAdmin.emailSet.inputRulesProm'), trigger: 'blur' }
          ],
          mailPort: [{ required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'blur' }],
          username: [
            { required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'blur' },
            { min: 1, max: 50, message: this.$t('resourceAdmin.emailSet.inputRulesProm'), trigger: 'blur' }
          ],
          password: [{ required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'blur' }],
          mailPersonal: [
            { required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'blur' }
          ],
          state: [{ required: true, message: this.$t('resourceAdmin.emailSet.placeHolderSelect'), trigger: 'change' }],
          auth: [{ required: true, message: this.$t('resourceAdmin.emailSet.placeHolderSelect'), trigger: 'change' }],
          sender: [
            { required: true, message: this.$t('resourceAdmin.emailSet.placeHolderInput'), trigger: 'change' },
            {
              validator: this.validateEmail,
              message: this.$t('resourceAdmin.emailSet.emailRuleProm'),
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    watch: {
      'params.password': {
        handler(val) {
          if (val === '') {
            this.editPwd = true
          }
        },
        deep: true
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          this.$nextTick(() => {
            this.params = Object.assign(this.params, cloneDeep(info))
            this.params.state += ''
            this.editPwd = false
            this.params.password = '......'
          })
          return
        }
        this.title = this.$t('resourceAdmin.emailSet.add')
      },
      validateEmail(rule, value, callback) {
        if (value && value !== '' && !checkEmail(value)) {
          callback(new Error(this.$t('system.user.EmailAddresses')))
        } else {
          callback()
        }
      },
      handleSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.params,
              password: this.params.password === '......' ? '' : this.params.password
            }
            try {
              const { code, msg } = this.params.id
                ? await apiPutEditMailSetting(param)
                : await apiPostAddMailSetting(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.loading = false
        this.visible = false
      }
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep.el-input.is-disabled .el-input__inner,
  ::v-deep.el-textarea.is-disabled .el-textarea__inner {
    cursor: auto;
    color: #606266;
  }
</style>
